package cn.com.elite;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.encoding.XMLType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.elite.algorithm.GUID;


import sun.misc.BASE64Decoder;

public class RSThread implements Runnable{
	private static final Log log=LogFactory.getLog(RSThread.class);
	public static cn.com.elite.EliteBean ebeana;
	private boolean flag=true;
	private int HZ=1000*60*40;
	private String daytime="";
	private FTPFile[] ff=null;
	private String filename1="";
	private String name1="";
	private String name2="";
	private int judgeNum=0;
	private String[] date_judge;
	private String[] insert_content1;
	
	public static String ip;
	public static String port;
	public static String username;
	public static String password;
	public static String filename;
	public static String sqlname;
	public static String sqlname1;
	public static String result;
	public static String dotime;
	public static String path="";
	public static String InsertSql;
	public static String EXCEL_DATE;
	public static String insert_content;
	public static String insert_type;
	
	
	
	public static String getInsert_type() {
		return insert_type;
	}
	public static void setInsert_type(String insert_type) {
		RSThread.insert_type = insert_type;
	}
	public static String getInsert_content() {
		return insert_content;
	}
	public static void setInsert_content(String insert_content) {
		RSThread.insert_content = insert_content;
	}
	public static String getEXCEL_DATE() {
		return EXCEL_DATE;
	}
	public static void setEXCEL_DATE(String excel_date) {
		EXCEL_DATE = excel_date;
	}
	public static String getInsertSql() {
		return InsertSql;
	}
	public static void setInsertSql(String insertSql) {
		InsertSql = insertSql;
	}
	public static String getIp() {
		return ip;
	}
	public static void setIp(String ip) {
		RSThread.ip = ip;
	}
	public static String getPort() {
		return port;
	}
	public static void setPort(String port) {
		RSThread.port = port;
	}
	public static String getUsername() {
		return username;
	}
	public static void setUsername(String username) {
		RSThread.username = username;
	}
	public static String getPassword() {
		return password;
	}
	public static void setPassword(String password) { 
		RSThread.password = password;
	}
	public static String getFilename() {
		return filename;
	}
	public static void setFilename(String filename) {
		RSThread.filename = filename;
	}
	public static String getSqlname() {
		return sqlname;
	}
	public static void setSqlname(String sqlname) {
		RSThread.sqlname = sqlname;
	}
	public static String getSqlname1() {
		return sqlname1;
	}
	public static void setSqlname1(String sqlname1) {
		RSThread.sqlname1 = sqlname1;
	}
	public static String getResult() {
		return result;
	}
	public static void setResult(String result) {
		RSThread.result = result;
	}
	public static String getDotime() {
		return dotime;
	}
	public static void setDotime(String dotime) {
		RSThread.dotime = dotime;
	}
	public static String getPath() {
		return path;
	}
	public static void setPath(String path) {
		RSThread.path = path;
	}
	public static Log getLog() {
		return log;
	}
	public cn.com.elite.EliteBean getEbeana() {
		return ebeana;
	}
	public void setEbeana(cn.com.elite.EliteBean ebeana) {
		this.ebeana=ebeana;
	}
	private boolean judge_excel(String a){
		try{
			if(date_judge!=null&&date_judge.length>0){
				for(int i=0;i<date_judge.length;i++){
					if(a.equals(date_judge[i])){
						return true;
					}
				}
			}else{
				return false;
			}
			return false;
		}catch(Exception e){
			log.error("judge_excel出错:"+EliteUtil.getERRO(e));    
			return false;
		}
	}
	private boolean copyFile(String oldPath,String newPath){
		try{
			int bytesum=0;     
	        int byteread=0;     
	        File oldfile=new File(oldPath);     
	        if(oldfile.exists()){ 
	        	InputStream inStream=new FileInputStream(oldPath);  //读入原文件     
	            FileOutputStream fs=new FileOutputStream(newPath);     
	            byte[] buffer=new byte[1444];     
	            int length; 
	            while((byteread=inStream.read(buffer))!=-1){
	            	bytesum+=byteread;  //字节数  文件大小       
	                fs.write(buffer,0,byteread); 
	            }
	            inStream.close(); 
	        }
	        return true;
		}catch(Exception e){
			log.error("复制单个文件操作出错:"+EliteUtil.getERRO(e));        
	        return false;
		}
	}
	 
	private void changeDirectory(String oldpath,String newpath,boolean cover){
		try{
			File oldfile=new File(oldpath);   
	        File newfile=new File(newpath);   
	        if(newfile.exists()){
	        	if(cover){
	            	oldfile.renameTo(newfile); //覆盖   
	            }else{
	            	log.info("在新目录下已经存在："); 
	            }
	        }else{
	        	if(copyFile(oldpath,newpath)==true){	        		
	        		oldfile.delete();
	        	}  
	        }
		}catch(Exception e){
			log.error("changeDirectory失败:"+EliteUtil.getERRO(e));
		}
	}
	private void CreateFile(String path){
		try{
			File dirFile=new File(path);
			if (!(dirFile.exists())&&!(dirFile.isDirectory())){
				boolean creadok=dirFile.mkdirs();
				if(creadok){
					log.info( " ok:创建文件夹成功！ " );
				}else{
					log.info( " err:创建文件夹失败！ " );
				}
			}
		}catch(Exception e){
			log.error("创建文件夹失败:"+EliteUtil.getERRO(e));
		}	
	}
	private FTPClient GetFtp(String host,int port,String username,String password){
		FTPClient ftp;
		ftp = new FTPClient(); 
		try{
			ftp.connect(host, port); 
			ftp.setControlEncoding("GBK");
			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
			conf.setServerLanguageCode("zh");			
			ftp.login(username, password);
		}catch(Exception e){
			log.error("FTP连接失败:"+EliteUtil.getERRO(e));
		}
		return ftp;
		
	}
	private void dorun(){
		try{
			String file_name="";
			FTPClient ftp=GetFtp(ip,Integer.parseInt(port),username,password);
			ftp.enterLocalPassiveMode();
			if(ftp!=null){
				Date date1=new Date();
				String dd1=String.format("%tF",date1); //获取现在几号
				dd1=dd1.replace("-", "");
				if(file_name.equals("")){
					file_name=file_name+dd1;
				}else{
					file_name=file_name+"/"+dd1;
				}
				ftp.changeWorkingDirectory("/callcenter/file");
				FTPFile[] ff1=ftp.listFiles();
				log.info("ff1.length:"+ff1.length);
				log.info("进入file_name:"+file_name);
				ff=ftp.listFiles(file_name);
				if(ff!=null&&ff.length>0){
					for(int i=0;i<ff.length;i++){
						filename1=ff[i].getName();
						log.info("filename1:"+filename1);
						if(filename1.length()<6){
							filename1=filename1+"1111111";
						}
						filename1=new String(filename1.getBytes("gbk"),"iso8859-1");
                        log.info("path:"+path);
                        List list11=ebeana.chaxun(" select * from XF_hflog where flag=1 and  descname='"+filename1+"' ");
                        String judge_flag1="fail";
                        if(list11!=null&&list11.size()>0){
			            	Map map=(Map)list11.get(0);
			            	String descname=(String)map.get("descname");
			            	if(descname!=null&&descname.equals(filename1)){
			            		judge_flag1="sucess";
			            	}
			            }
                        String aaaq=filename1.substring(3,6);
                        log.info("judge_flag1:"+judge_flag1);
                        log.info("aaaq:"+aaaq);
                        log.info("filename:"+filename);  
                        if(!judge_flag1.equals("sucess")&&aaaq.equals(filename)){
                        	name1=new String(filename1.getBytes("iso8859-1"), "gbk");
    						name1=name1.substring(0, name1.lastIndexOf("."));
    						name2=path+"\\"+new String(filename1.getBytes("iso8859-1"), "gbk");
    						File file=new File(name2);
    						FileOutputStream fos=new FileOutputStream(file);
    						boolean flag=ftp.retrieveFile(file_name+"/" + filename1, fos);
    						fos.close();
    						FileInputStream is = new FileInputStream(new File(name2)); 
    						ByteArrayOutputStream byteOS = new ByteArrayOutputStream(); 
    						byte[] by=new byte[512];  
    						int t=is.read(by,0,by.length); 
    						while(t>0){
    							byteOS.write(by,0,512);  //这里别写成t，写够512，呵呵，SB的方法对付SB的java API
   							    t=is.read(by,0,by.length); 
    						}
    						byteOS.close(); 
    						InputStream byteIS = new ByteArrayInputStream(byteOS.toByteArray());  
    				        HSSFWorkbook wb=new HSSFWorkbook(byteIS);
    				        HSSFSheet childSheet = wb.getSheetAt(0);   
    				        int rowNum=childSheet.getLastRowNum()+1;
    				        int size=rowNum-1;
    				        String[][] data=new String[size][90];
    				        SimpleDateFormat DateFormat=new SimpleDateFormat("yyyy-MM-dd"); 
    				        for(int j=1;j<rowNum;j++){
    				        	HSSFRow row = childSheet.getRow(j);    
    			                int cellNum=row.getLastCellNum(); 
    			                for(int k=0;k<cellNum;k++){
    			                	HSSFCell cell=row.getCell((short) k);
    			            		if(cell==null){
    			            			data[j-1][k]="";
    			            		}else if(cell.getCellType()==3){
    			                		data[j-1][k]="";
    			                	}else if(cell.getCellType()==1){
    			                    		String a=cell.toString();
    			                			data[j-1][k]=cell.toString();
    			                	}else if(cell.getCellType()==0){
    			                		if(HSSFDateUtil.isCellDateFormatted(cell)||judge_excel(k+"")){
    			                			data[j-1][k]= DateFormat.format(cell.getDateCellValue());
    			                        	if(data[j-1][k].length()>19){
    			                        	  data[j-1][k]= DateFormat.format(cell.getDateCellValue()).substring(0,19);
    			                        	}
    			                		}else{
    			                			double a=cell.getNumericCellValue();
			                        		data[j-1][k]=a+"";
    			                		}
    			                	}else if(HSSFCell.CELL_TYPE_BLANK == cell.getCellType()){
    			                		data[j-1][k]="";
    			                	}
    			                }
    				        }  				        
    				        
    				        String[] s;  
    			            s=new String[data.length];	
    			            
    			            int[] types=getType(insert_type);
    			            Object[] ContentParam=getContent(insert_content,data);
    			            log.info("ContentParam.length:"+ContentParam.length);
    			            if(ContentParam!=null&&ContentParam.length>0){
    							for(int n=0;n<ContentParam.length;n++){
    								String insertresult=ebeana.insertPersonUseExecute(InsertSql,types,(Object[])ContentParam[n]);
    								log.info("insertresult:"+insertresult);
    							}
    						}

    			            
    			            Date date=new Date();
    						String dd=String.format("%tF",date); //获取现在几号
    						dd=dd.replace("-", "");							
    			            String guid=new GUID().toString();
    			            String url=path+"\\"+dd+"\\"+new String(filename1.getBytes("iso8859-1"), "gbk");
    			            String sql123=" insert into XF_hflog(descname,URL,flag,rqname,GUID)Values('"+filename1+"','"+url+"',1,'"+name2+"','"+guid+"')";
    			            List list1=ebeana.chaxun(" select * from XF_hflog where GUID='"+guid+"'  ");
    			            String judge_flag="fail";
    			            if(list1!=null&&list1.size()>0){
    			            	Map map=(Map)list1.get(0);
    			            	String GUID=(String)map.get("GUID");
    			            	if(GUID!=null&&GUID.equals(guid)){
    			            		judge_flag="sucess";
    			            	}
    			            }
    			            if(judge_flag.equals("sucess")){
    			            	CreateFile(path+"\\"+dd);
    			            	changeDirectory(name2,path+"\\"+dd+"\\"+new String(filename1.getBytes("iso8859-1"), "gbk"),true);
    			            	judgeNum=1;
    			            }else{
    			            	String sql1234=" insert into XF_hflog(descname,flag,GUID)Values('"+filename1+"',2,'"+guid+"')";
   			            	    log.info("sql1234:"+sql1234);
   			            	    ebeana.update(sql1234);
    			            }
                        }
					}
				}
			}else{
				ftp.logout();
				ftp.disconnect();
				log.info("没有获得"+file_name+"路径下文件目录");
			}
		}catch(Exception e){
			log.error("dorun()执行过程错误:"+EliteUtil.getERRO(e));  
		}
	}
	private Object[] getContent(String InsertContent,String[][] data){
		log.info("InsertContent:"+InsertContent);
		if(InsertContent!=null&&!InsertContent.equals("")&&InsertContent.length()>0){
			try{
				String[] content=InsertContent.split(",");
				Object[] ContentParam=new Object[data.length];
				for(int i1=0;i1<data.length;i1++){
					Object[] params=new Object[content.length];
					for(int i2=0;i2<content.length;i2++){
						int index=Integer.parseInt(content[i2]);
						if(data[i1][index]==null||data[i1][index].toString().equals("")){
							params[i2]=null;
						}else{				
							params[i2]=data[i1][index];	
						}
					}
					ContentParam[i1]=params;
				}
				return ContentParam;
			}catch(Exception e){
				log.info("获得内容失败:"+EliteUtil.getERRO(e));  
				return null;
			}
		}else{
			log.info("获得内容失败");  
			return null;
		}
	}
	private int[] getType(String InsertSqlType){
		if(InsertSqlType!=null&&!InsertSqlType.equals("")&&InsertSqlType.length()>0){
			try{
				String[] sqltype=InsertSqlType.split(",");
				log.info("sqltype:"+sqltype);  
				if(sqltype!=null&&sqltype.length>0){
					int[] types=new int[sqltype.length];
					for(int i=0;i<sqltype.length;i++){
						if(sqltype[i].equals("CHAR")){
							types[i]=Types.VARCHAR;
						}else if(sqltype[i].equals("INT")){
							types[i]=Types.INTEGER;
						}else if(sqltype[i].equals("DATE")){
							types[i]=Types.DATE;
						}else{
							log.info("获得参数类型失败:"+i+":"+sqltype[i]);  
							return null;
						}
					}
					return types;
				}else{
					return null;
				}
			}catch(Exception e){
				log.info("获得参数类型失败:"+EliteUtil.getERRO(e));  
				return null;
			}			
		}else{
			log.info("获得参数类型失败");  
			return null;
		}
	}
	public void run(){
	    log.info("-------------------------RSThread---------------------------------");
		while(flag){
			try{
				date_judge=EXCEL_DATE.split(",");
				insert_content1=insert_content.split(",");
				Date date=new Date();
				String ee=String.format("%tR",date); //获取现在几点
				String dd=String.format("%tF",date); //获取现在几号
				String now1=ee.substring(0,2);
				log.info("dd:"+dd);
				log.info("daytime:"+daytime);
				log.info("now1:"+now1);
				if(now1.equals(dotime)&&!dd.equals(daytime)){
					dorun();
					daytime=dd;
				}
			}catch(Exception e){
				log.error("RSThread执行过程错误:"+EliteUtil.getERRO(e));  
			}
			try{
				Thread.sleep(HZ);
			}catch(Exception e){
				log.error("RSThread休眠错误:"+EliteUtil.getERRO(e));  
			}
		}

	}

}
